<?php

namespace app\common\controller;

/**
 * 微信授权相关接口
 *
 * @link http://www.phpddt.com
 */
class Wechat extends Common
{
//高级功能-》开发者模式-》获取
    public $app_id = 'wx99dfcc9156470c51'; //公众号appid
    private $app_secret = 'cf885f9a0d9e26e61ffba2eaa854f16f'; //公众号app_secret
    public $noncestr = "12d34aabb123f4";
    private $key = '0909bc7bef4a1116126b2cc742f90f58';
    public $redirect_uri = 'http://nmb.lhtxsm.com/index/User/getOpenId'; //授权之后跳转地址

    /**
     * 获取微信授权链接
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($url = '', $state = 'WECHAT')
    {
        if (!$url) {
            $url = $this->redirect_uri;
        }
        $this->redirect_uri = $url;

        $redirect_uri = urlencode($url);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
    }

    /**
     * 获取授权token
     *
     * @param string $code 通过get_authorize_url获取到的code
     */
    public function get_access_token($code)
    {
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}&code={$code}&grant_type=authorization_code";
        $token_data = $this->http($token_url);


        if ($token_data[0] == 200) {
            return json_decode($token_data[1], TRUE);
        }

        return FALSE;
    }

    public function get_token()
    {
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->app_id}&secret={$this->app_secret}";
        $data = $this->http($token_url);
        if ($data[0] == 200) {
            return json_decode($data[1], true);
        }

        return false;
    }

    /**
     * 获取授权后的微信用户信息
     * @param string $access_token
     * @param string $open_id
     */
    public function get_user_info($access_token, $open_id)
    {
        if ($access_token && $open_id) {
            /* $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";*/
            $info_url = "api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
            $info_data = $this->http($info_url);
            
            if ($info_data[0] == 200) {
                return json_decode($info_data[1], TRUE);
            }
        }

        return FALSE;
    }

    public function http($url, $method = 'post', $postfields = null, $headers = array(), $debug = false)
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                    $this->postdata = $postfields;
                }
                break;
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);

            echo '=====info=====' . "\r\n";
            print_r(curl_getinfo($ci));

            echo '=====$response=====' . "\r\n";
            print_r($response);
        }
        curl_close($ci);
        return array($http_code, $response);
    }


    public function payment($openId, $total)
    {
        $key = $this->key;
        $mchid = '1243139902';//商户号
        $check_name = 'NO_CHECK';//校验用户姓名选项，NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账）OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
        $amount = $total * 100;//金额（以分为单位，必须大于100）
        $desc = 'shshi';//描述
        $spbill_create_ip = $_SERVER["REMOTE_ADDR"];//请求ip
        /*封装数据*/
        $dataArr = [
            'mch_appid' => $this->app_id,//商户账号appid
            'mchid' => $mchid,//商户号
            'nonce_str' => self::createNoncestr(),//随机字符串
            'partner_trade_no' => date('YmdHis') . rand(1000, 9999),//商户订单号
            'openid' => $openId,//用户openid
            'check_name' => 'NO_CHECK',//校验用户姓名选项,
            'amount' => $amount,//金额
            'desc' => $desc,//企业付款描述信息
            'spbill_create_ip' => $spbill_create_ip,//Ip地址
        ];

        foreach ($dataArr as $k => $v) {
            $tarr[] = $k . '=' . $v;
        }
        sort($tarr);
        $sign = implode($tarr, '&');
        $sign .= '&key=' . $key;
        $dataArr['sign'] = strtoupper(md5($sign));
        $data = self::arraytoxml($dataArr);

        $postUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        $curlPost = $data;
        $ch = curl_init();                                      //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl);                 //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSLCERT, '/www/wwwroot/sh1149.cmsc888.com/sh1149/web/apiclient_cert.pem'); //这个是证书的位置绝对路径
        curl_setopt($ch, CURLOPT_SSLKEY, '/www/wwwroot/sh1149.cmsc888.com/sh1149/web/apiclient_key.pem'); //这个也是证书的位置绝对路径
        $result = curl_exec($ch);                                 //运行curl
        $responseObj = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
        $responseArr = json_decode(json_encode($responseObj), true);
        if ($responseArr["return_code"] == 'SUCCESS') {
            //TODO 成功
            if ($responseArr["result_code"] == 'SUCCESS') {
                //TODO 成功
                return ['status' => 1, 'msg' => '成功'];
            } else {
                return ['status' => 0, 'msg' => $responseArr['err_code_des']];
            }
        } else {
            return ['status' => 0, 'msg' => $responseArr['return_msg']];
        }
    }

    function createNoncestr($length = 32)
    {

        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";

        $str = "";

        for ($i = 0; $i < $length; $i++) {

            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);

        }
        return $str;
    }

    function arraytoxml($data)
    {
        $str = '<xml>';
        foreach ($data as $k => $v) {
            $str .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        $str .= '</xml>';
        return $str;
    }

    public function getSign($Obj, $key)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = self::formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String . $key;
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }

    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /**
     * 分享
     * @param $timestamp
     * @return bool|string
     */
    public function share($timestamp)
    {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $appurl = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        if (!$appurl) {
            $this->error('请输入链接！');
        }

        $appurl = str_replace("__", "&", $appurl);

        $file = "access_token.txt";

        if (file_exists($file)) {

            $fp = fopen($file, "r");

            $access_token = fread($fp, filesize($file));

        } else {

            $access_token = self::getToken($file);

        }

        //获取jsticket
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $access_token . "&type=jsapi";

        $rurl = file_get_contents($url);

        $rurl = json_decode($rurl, true);

        if ($rurl['errcode']) {

            $access_token = self::getToken($file);

            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $access_token . "&type=jsapi";

            $rurl = file_get_contents($url);

            $rurl = json_decode($rurl, true);

            $jsapi_ticket = $rurl['ticket'];

        } else {

            $jsapi_ticket = $rurl['ticket'];

        }

        $string1 = 'jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $this->noncestr . '&timestamp=' . $timestamp . '&url=' . $appurl;

        $signature = sha1($string1);

        return $signature;

    }

    /**
     * 得到token
     * @param $file
     * @return mixed
     */
    public function getToken($file)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;

        $rurl = file_get_contents($url);

        $rurl = json_decode($rurl, true);

        $access_token = $rurl['access_token'];

        $fp = fopen($file, 'w');

        fwrite($fp, '');

        fwrite($fp, $access_token);

        return $access_token;
    }

    /**
     * 小程序获取openid
     * @return string
     */
    public function get_open_id_wechat($code, $appId, $key)
    {
        $curl = curl_init();
        //使用curl_setopt() 设置要获得url地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $key . '&js_code=' . $code . '&grant_type=authorization_code';
        curl_setopt($curl, CURLOPT_URL, $url);

        //设置是否输出header
        curl_setopt($curl, CURLOPT_HEADER, false);

        //设置是否输出结果
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        //设置是否检查服务器端的证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        //使用curl_exec()将curl返回的结果转换成正常数据并保存到一个变量中
        $data = curl_exec($curl);

        //关闭会话
        curl_close($curl);
        p($data);
    }
  
    /**
     * 获取小程序的openid
     * @return mixed
     */
    public function wxGetOpenidByCode()
    {
        $code = input('code');//获取code
        $appid = "wx0c7baa249e41dd4d";
        $secret = "39e4bc43f32852c11cf7ff7aa5cd4daa";
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        //通过code换取网页授权access_token
        $weixin = file_get_contents($url);
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        $openid = $array['openid'];//输出openid
     
        return $openid;
    }
}
